#include "bcd.h"
#include "cmsis_os.h"
#include "param.h"

/*************************************
*说明：	该8421编码器，引脚和实际的编码值成补码的关系。比如编码的0-对应引脚的0X0F  1-对应引脚上的0X0E
*				所以通过引脚读取回来的值需要用0X0F-value 才是对应的编码器上标的值
*************************************/

uint8_t bcdValue[BCD_MAX];  //这里存放的是4个引脚组成的值，实际值应该是他的补码
static uint8_t bcdState[BCD_MAX];

void bcd_init()
{
	uint8_t bl1,bl2,bl4,bl8;
	bl1=HAL_GPIO_ReadPin(BCD1L_GPIO_Port,BCD1L_Pin);
	bl2=HAL_GPIO_ReadPin(BCD2L_GPIO_Port,BCD2L_Pin);
	bl4=HAL_GPIO_ReadPin(BCD4L_GPIO_Port,BCD4L_Pin);
	bl8=HAL_GPIO_ReadPin(BCD8L_GPIO_Port,BCD8L_Pin);
	bcdValue[BCD_L]=(bl1+(bl2<<1)+(bl4<<2)+(bl8<<3));
	
	bl1=HAL_GPIO_ReadPin(BCD1M_GPIO_Port,BCD1M_Pin);
	bl2=HAL_GPIO_ReadPin(BCD2M_GPIO_Port,BCD2M_Pin);
	bl4=HAL_GPIO_ReadPin(BCD4M_GPIO_Port,BCD4M_Pin);
	bl8=HAL_GPIO_ReadPin(BCD8M_GPIO_Port,BCD8M_Pin);
	bcdValue[BCD_M]=(bl1+(bl2<<1)+(bl4<<2)+(bl8<<3));
	
	for(uint8_t i=0;i<BCD_MAX;i++)
	{
		bcdState[i]=0;
	}
}

void bcd_poll()
{
	static uint8_t counter=0;
	uint8_t bl1,bl2,bl4,bl8;
	uint8_t nowValue[BCD_MAX];

	bl1=HAL_GPIO_ReadPin(BCD1L_GPIO_Port,BCD1L_Pin);
	bl2=HAL_GPIO_ReadPin(BCD2L_GPIO_Port,BCD2L_Pin);
	bl4=HAL_GPIO_ReadPin(BCD4L_GPIO_Port,BCD4L_Pin);
	bl8=HAL_GPIO_ReadPin(BCD8L_GPIO_Port,BCD8L_Pin);
	nowValue[BCD_L]=(bl1+(bl2<<1)+(bl4<<2)+(bl8<<3));

	bl1=HAL_GPIO_ReadPin(BCD1M_GPIO_Port,BCD1M_Pin);
	bl2=HAL_GPIO_ReadPin(BCD2M_GPIO_Port,BCD2M_Pin);
	bl4=HAL_GPIO_ReadPin(BCD4M_GPIO_Port,BCD4M_Pin);
	bl8=HAL_GPIO_ReadPin(BCD8M_GPIO_Port,BCD8M_Pin);
	nowValue[BCD_M]=(bl1+(bl2<<1)+(bl4<<2)+(bl8<<3));

	for(uint8_t i=0;i<BCD_MAX;i++)
	{
			switch (bcdState[i])
			{
				case 0:
					if(nowValue[i]!=bcdValue[i])  	//检测到状态改变
					{
						bcdState[i]=1;
						counter=0;
					}
					break;
				case 1:
					counter++;
					if(counter>=5)
					{
						counter=0;
						if(nowValue[i]!=bcdValue[i])	//确定发生了改变
						{
							bcdValue[i]=nowValue[i];
						}
						bcdState[i]=0;
					}
					break;
			}
	}
}
uint8_t bcd_getValue(bcd_type b)
{
	uint8_t value=0X0F-bcdValue[b];
	return value;
}


void BcdTask(void const * argument)
{
  for(;;)
  {
		bcd_poll();
    osDelay(10);
  }
}
